/*
 * @Author: YinJianFeng 814922893@qq.com
 * @Date: 2025-01-22 13:53:55
 * @LastEditors: 殷建峰
 * @LastEditTime: 2025-02-25 15:26:55
 */
import { FeatureManager } from '@amcax/base';
import { TabRightExtraContent } from './TabRightExtraContent';
import { FullscreenExitOutlined, FullscreenOutlined } from '@ant-design/icons';
import { Tabs } from 'antd';
import { userEvents } from 'nextcae-base';
import React, { useEffect } from 'react';
import { ToolBarEvents } from '../CmdBar/CmdBottomBtn/type';
import { ICommandLayout } from '../types';
import styles from './styles.module.scss';
import TabContent from './TabContent';
import { TabLeftExtraContent } from './TabLeftExtraContent';

export interface IProps {
  cmdLayouts: ICommandLayout[];
}

type PositionType = 'left' | 'right';

export default function Header({ cmdLayouts }: IProps) {
  const [fullscreen, setFullscreen] = React.useState(false);
  const items = cmdLayouts.map((cmdLayout) => {
    return {
      label: cmdLayout.label,
      key: cmdLayout.id,
      children: <TabContent cmdGroups={cmdLayout.cmds} />,
    };
  });

  const extraSlot: Record<PositionType, React.ReactNode> = {
    left: FeatureManager.isFeatureEnabled('cmdbar-standard') ? (
      <TabLeftExtraContent />
    ) : null,
    right: FeatureManager.isFeatureEnabled('cmd-tools') ? (
      <TabRightExtraContent />
    ) : null,
  };
  function enterFullscreen() {
    if (!document.fullscreenEnabled) {
      return Promise.reject(new Error('全屏模式被禁用'));
    }
    document.documentElement.requestFullscreen();
    return Promise.resolve();
  }
  // 处理按键事件
  function exitFullscreen() {
    if (!document.fullscreenElement) {
      return Promise.reject(new Error('当前不是全屏模式'));
    }
    document.exitFullscreen();
    return Promise.resolve();
  }
  useEffect(() => {
    // 退出全屏时移除监听;
    document.addEventListener('fullscreenchange', () => {
      setFullscreen(!!document.fullscreenElement);
    });
  }, []);
  return (
    <div className={styles.header}>
      <Tabs
        defaultActiveKey='1'
        className={styles.tabs}
        type='card'
        size='small'
        items={items}
        tabBarExtraContent={extraSlot}
        onChange={(id) => {
          userEvents.emit(ToolBarEvents.TAB_CHANGE, id);
        }}
      />
      <div className={styles.rightBody}>
        <div className={styles.fullscreen}>
          {fullscreen ? (
            <FullscreenExitOutlined
              style={{ color: 'white' }}
              onClick={exitFullscreen}
            />
          ) : (
            <FullscreenOutlined
              style={{ color: 'white' }}
              onClick={enterFullscreen}
            />
          )}
        </div>
      </div>
    </div>
  );
}
